import { loginByPhone, loginByUsername, logout, getUserInfo, getMenu } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setStore, getStore } from '@/utils/store'
import { isURL, validatenull } from '@/utils/validate'
import { deepClone } from '@/utils/util'
import { resetRouter } from '@/router'
import website from '@/config/website'
import { baseUrl } from '@/config/env';

//添加菜单
function addPath(item,first){

  const menu = website.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  //图标
  const icon = item[propsDefault.icon];
  item[propsDefault.icon] = validatenull(icon) ? menu.icon : icon;
  //子菜单
  item[propsDefault.children] = item[propsDefault.children] || [];
  //是否有子菜单
  const isChild = item[propsDefault.children] && item[propsDefault.children].length !== 0;
  //没有子菜单，顶级目录，不是http第三方链接
  if(!isChild && first && !isURL(item[propsDefault.path])){
    item[propsDefault.path] = item[propsDefault.path] + '/index'
  } else{
    item[propsDefault.children].forEach(child => {
      if(!isURL(child[propsDefault.path])){
        child[propsDefault.path] = `${item[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
      }
      addPath(child);
    })
  }
}







const state = {
  token: getToken() || '',
  roles: [],
  userInfo:{},
  permission:{},
  avatar:'',
  menu: getStore({name:'menu'}) || [],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    //保存token
    setToken(token);
    state.token = token;
    setStore({name:'token',content:state.token,type:'session'})
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_ROLES: (state,roles) => {
    state.roles = roles;
  },
  SET_AVATAR: (state,avatar) =>{
    state.avatar = baseUrl+avatar+'?jstime='+(new Date().getTime());
  },
  SET_PERMISSION: (state,permission) => {
    state.permission = {};
    permission.forEach(item => {
      const key = item.replace('/','').replace('/','_');
      state.permission[key] = true;
    })
  },
  //系统菜单
  SET_MENU: (state,menu) =>{
    state.menu = menu;
    setStore({name:'menu',content:state.menu,type:'session'})
  }
}

const actions = {
  //用户名登录
  loginByUsername({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginByUsername({ username: username.trim(), password: password }).then(response => {
        const { data } = response;

        console.log("登录成功后获取token:"+data.data);

        commit('SET_TOKEN', data.data)
        //处理删除所有tag

        //清除锁屏
        data.data ? resolve(data) : reject(data);
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 手机验证码登录
  loginByPhone({ commit }, userInfo) {
    const { phone, smsCode } = userInfo;
    return new Promise((resolve, reject) => {
      loginByPhone({ phone: phone.trim(), smsCode: smsCode }).then(response => {
        const { data } = response
        data.data = data.data.token;
        data.userId = data.data.userId;
        console.log("手机号码登录成功后获取token:"+data.data);

        commit('SET_TOKEN', data.data)
        //处理删除所有tag

        //清除锁屏

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  

  
  //获取用户信息
  GetUserInfo ({ commit }) {

    return new Promise((resolve,reject) => {
      getUserInfo().then((res) => {
        console.log(res.data.data, "--------获得用户信息----------")
        const data = res.data.data;
        //data.avatar = data.avatar+'?jstime='+(new Date().getTime())
        commit('SET_AVATAR',data.avatar);
        commit('SET_USERINFO',data);
        commit('SET_ROLES',data.roleList);
        commit('SET_PERMISSION',data.permissions)
        resolve(data);
      }).catch(err => {
        reject(err);
      });
    });

  },

  // 登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '');


        removeToken()

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  //注销session
  FedLogOut ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');

      removeToken();
      resolve();
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  //获取系统菜单
  GetMenu ({ commit },parentId) {
    return new Promise(resolve => {
      getMenu(parentId).then((res) => {
        console.log("----------获取系统菜单------------")
        const data = (res.data.data[0] || {}).subMenus;
        

        //克隆菜单
        let menu = deepClone(data) || [];
        menu.forEach(item => {
          addPath(item,true)
        });
        commit('SET_MENU',menu);
        //console.log(menu);
        resolve(menu)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

